package zozopo.manual.image;
import java.awt.Dimension;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import magick.ImageInfo;
import magick.MagickApiException;
import magick.MagickException;
import magick.MagickImage;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import zozopo.manual.operations.ContentImagesOS;
import zozopo.manual.operations.ContentImagesTB;

import zozopo.user.operations.UserTB;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class UploadImageAction extends ActionSupport implements Action ,SessionAware,ServletRequestAware,ServletResponseAware{
	
	private static final int BUFFER_SIZE = 16 * 1024;
	private static final String UPLOAD_PATH = "/manual/content";
	
	//private static int selectNo = 0;
	
	// 输入参数:上传过来的文件路径
	private File file;
	private String imageFileName;
	private int imageNumber ;
	private int contentId;

	// 输出参数
	private String imageUrl;
	private String smallImageUrl;
	
	
	public String execute(){
		
		
		//权限处理
		UserTB user = (UserTB)session.get("userInfo");
		if(user == null){
			try {
				response.setCharacterEncoding("gb2312");  //这可以使正确提示
				response.getWriter().write("{\"error\":\"用户未登陆\"}");
				response.getWriter().flush();
				response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			return NONE;
			
		}
		
		ContentImagesTB contentImages;
		ContentImagesOS contentImagesOS1 = new ContentImagesOS();

		try{
			contentImages = contentImagesOS1.getByContentId(contentId);
		}finally{
			contentImagesOS1.releaseConnection();
		}
		
		if(contentImages.getUser_id() != user.getId_user()){   //验证content是否为当前用户 Content
			try {
				response.setCharacterEncoding("gb2312");  //这可以使正确提示
				response.getWriter().write("{\"error\":\"用户登陆冲突请刷新后再上传图片\"}");
				response.getWriter().flush();
				response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  //返回小图连接
			return NONE;
		}
		
		
		
		
		//开始处理上传
		String abstractPath = UPLOAD_PATH;
		
		Calendar calendar =Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		
		imageFileName = contentId +""+ imageNumber + getExtention(imageFileName); 
		
		imageFileName =  new Date().getTime() + imageFileName;

		// 得到文件存放路径
		String dir = ServletActionContext.getServletContext().getRealPath(UPLOAD_PATH);
		
		File dirs = new File(dir);
		if (!dirs.exists()){
			dirs.mkdir();
		}
		
		//生成年份路径
		dir = dir +"/"+ year;
		abstractPath = abstractPath+"/"+ year;
		
		dirs = new File(dir);
		
		if (!dirs.exists()){
			dirs.mkdir();
		}
		
		//生成目录路径
		dir = dir +"/"+ contentId;
		abstractPath = abstractPath+"/"+ contentId;
		
		dirs = new File(dir);
		
		if (!dirs.exists()){
			dirs.mkdir();
		}
		
		//生成储存图片路径
		dir = dir +"/images";
		abstractPath = abstractPath+"/images";
		
		dirs = new File(dir);
		if (!dirs.exists()){
			dirs.mkdir();
		}
		
		//生成储存小图片路径
		dirs = new File(dir+"/small");
		if (!dirs.exists()){
			dirs.mkdir();
		}
		
		

		// 使用原来的文件名保存图片
		String path = dir + "/" + imageFileName;
		imageUrl = abstractPath+ "/" + imageFileName;
		smallImageUrl = abstractPath + "/small/" + imageFileName;
		
		
		File imageFile = new File(path);
		System.out.println(path);
		
		
		ContentImagesOS contentImagesOS = new ContentImagesOS();
		
		try {
			copy(file, imageFile);//保存图片
			smallImage(path,dir + "/small/" + imageFileName);//成生小图
			response.getWriter().write("{\"smallImageUrl\":\"" + smallImageUrl + "\",\"imageUrl\":\"" + imageUrl +"\"}");  //返回小图连接
			
			response.getWriter().flush();
			response.getWriter().close();
			
			if(contentImagesOS.isExit(contentId)){
				//更新新图片地址
				if(!contentImagesOS.update(contentId, imageNumber, imageUrl, smallImageUrl)){
					throw new Exception();
				} 
			}else{
				//插入新图片地址
				if(!contentImagesOS.insert(contentId,user.getId_user(), imageNumber, imageUrl, smallImageUrl)){
					throw new Exception();
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			contentImagesOS.releaseConnection();
		}
		
		return NONE;
	}
	


	
	private static void copy(File src, File dist) throws Exception {
		try {
		InputStream in = null;
		OutputStream out = null;
		try {
		in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
		out = new BufferedOutputStream(new FileOutputStream(dist), BUFFER_SIZE);

		byte[] buf = new byte[BUFFER_SIZE];
		while (in.read(buf) > 0) {
		out.write(buf);
		}
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		if (in != null)
		in.close();
		if (out != null)
		out.close();
		}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}

	}
	
	/** 
     * 输出缩放图片
     */ 
    public static void smallImage(String srcImage, String DestImage){
    
    System.setProperty("jmagick.systemclassloader","no");
    
    try{  

       ImageInfo info = new ImageInfo(srcImage);
       MagickImage image = new MagickImage(info);
      
       //取长宽
       Dimension dim = image.getDimension();
       double wImage = dim.getWidth();
       double hImage = dim.getHeight();
       
       
     //  System.out.println(wImage + " * " +hImage);
      
       
       if(wImage>192){
    	   double mul = wImage/192;
    	   wImage = wImage/mul;
    	   hImage = hImage/mul;
       }else{   //如果不需要压缩
			copy(new File(srcImage),new File(DestImage));
		}
      //输出
       MagickImage scaled = image.scaleImage((int)wImage, (int)hImage);
      
       
       scaled.setFileName(DestImage);   
       scaled.writeImage(info);  

      }catch(MagickApiException ex){
       }catch(MagickException ex){
    	   
       } catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    }
	
	
	/**
	 * 获取文件后缀
	 */
	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}
	
	private Map<Object, Object> session;
	private HttpServletRequest request;
	private HttpServletResponse response;
	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		session = arg0;
	}
	
	
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}

	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		request = arg0;
	}


	public File getFile() {
		return file;
	}


	public void setFile(File file) {
		this.file = file;
	}




	public String getImageFileName() {
		return imageFileName;
	}


	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}


	public int getImageNumber() {
		return imageNumber;
	}


	public void setImageNumber(int imageNumber) {
		this.imageNumber = imageNumber;
	}
	
	/*
	 * 获得上传文件名称。
	 * */
	public void setFileFileName(String fileName) {
		this.imageFileName = fileName;
	}


	public int getContentId() {
		return contentId;
	}


	public void setContentId(int contentId) {
		this.contentId = contentId;
	}





	public String getSmallImageUrl() {
		return smallImageUrl;
	}


	public void setSmallImageUrl(String smallImageUrl) {
		this.smallImageUrl = smallImageUrl;
	}


	public String getImageUrl() {
		return imageUrl;
	}


	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}



	
}
 